// admin.js
// 管理端页面脚本，后续可扩展具体管理功能

document.addEventListener('DOMContentLoaded', function() {
    // 欢迎模态框相关
    const welcomeModal = document.getElementById('welcome-modal');
    const welcomeCloseBtn = document.getElementById('welcome-close-btn');
    const welcomeCloseIcon = welcomeModal.querySelector('.close-btn');
    
    // 检查是否首次访问或需要显示欢迎模态框
    function shouldShowWelcome() {
        const lastVisit = localStorage.getItem('adminLastVisit');
        const now = new Date().getTime();
        const oneDay = 24 * 60 * 60 * 1000; // 24小时
        
        // 如果没有访问记录或超过24小时，显示欢迎模态框
        if (!lastVisit || (now - parseInt(lastVisit)) > oneDay) {
            localStorage.setItem('adminLastVisit', now.toString());
            return true;
        }
        return false;
    }
    
    // 显示欢迎模态框
    function showWelcomeModal() {
        welcomeModal.style.display = 'block';
    }
    
    // 隐藏欢迎模态框
    function hideWelcomeModal() {
        welcomeModal.style.display = 'none';
    }
    
    // 绑定关闭事件
    welcomeCloseBtn.addEventListener('click', hideWelcomeModal);
    welcomeCloseIcon.addEventListener('click', hideWelcomeModal);
    
    // 点击模态框外部关闭
    welcomeModal.addEventListener('click', function(e) {
        if (e.target === welcomeModal) {
            hideWelcomeModal();
        }
    });
    
    // 检查是否需要显示欢迎模态框
    if (shouldShowWelcome()) {
        // 延迟显示，让页面先加载完成
        setTimeout(showWelcomeModal, 500);
    }

    // 侧边栏菜单切换高亮
    const menuLinks = document.querySelectorAll('.admin-menu a');
    const routesSection = document.getElementById('routes-manage-section');
    const cultureSection = document.getElementById('culture-manage-section');
    // 分页查询相关
    const routeOrdersTbody = document.getElementById('route-orders-tbody');
    const routeOrdersPagination = document.getElementById('route-orders-pagination');
    let routeCurrentPage = 1;
    let routePageSize = 10;

    // 文化活动订单管理分页相关
    const activityOrdersTbody = document.querySelector('#culture-manage-section tbody');
    const activityOrdersPagination = document.getElementById('activity-orders-pagination');
    const activityFilterBtns = document.querySelectorAll('#culture-manage-section .filter-btn');
    let activityCurrentPage = 1;
    let activityPageSize = 10;
    let activityCurrentStatus = 'all';

    // 删除弹窗相关
    const confirmDeleteModal = document.getElementById('confirm-delete-modal');
    const cancelDeleteBtn = document.getElementById('cancel-delete-btn');
    const confirmDeleteBtn = document.getElementById('confirm-delete-btn');
    let deleteOrderInfo = null; // {type: 'route'|'activity', id: xxx}

    async function fetchRouteOrders(page = 1, size = 10) {
        try {
            const res = await fetch(`http://localhost:8080/api/orders/route?current=${page}&size=${size}`);
            const data = await res.json();
            // 适配后端返回 { records: [...], total, size, current }
            if (data.code === 200 && data.data) {
                renderRouteOrders(data.data.records || []);
                renderRoutePagination(data.data.total || 0, data.data.current || 1, data.data.size || 10);
            } else {
                routeOrdersTbody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
                routeOrdersPagination.innerHTML = '';
            }
        } catch (e) {
            routeOrdersTbody.innerHTML = '<tr><td colspan="7">加载失败</td></tr>';
            routeOrdersPagination.innerHTML = '';
        }
    }

    function getRouteDisplayName(route) {
        switch(route) {
            case 'culture': return '自然风光之旅';
            case 'nature': return '历史文化之旅';
            default: return route || '';
        }
    }

    function renderRouteOrders(list) {
        if (!list.length) {
            routeOrdersTbody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
            return;
        }
        routeOrdersTbody.innerHTML = list.map(order => `
            <tr>
                <td>${order.id}</td>
                <td>${order.username || ''}</td>
                <td>${getRouteDisplayName(order.route)}</td>
                <td>${order.date || ''}</td>
                <td>${order.people || ''}</td>
                <td>${order.phone || ''}</td>
                <td>
                    <button class="btn-edit" data-order='${JSON.stringify(order)}' title="编辑"><i class="fa fa-pencil"></i></button>
                    <button class="btn-delete" title="删除"><i class="fa fa-trash"></i></button>
                </td>
            </tr>
        `).join('');
    }

    function renderRoutePagination(total, page, size) {
        const pageCount = Math.ceil(total / size);
        let html = '';
        for (let i = 1; i <= pageCount; i++) {
            html += `<button class="page-btn${i === page ? ' active' : ''}" data-page="${i}">${i}</button>`;
        }
        routeOrdersPagination.innerHTML = html;
        // 绑定分页点击
        routeOrdersPagination.querySelectorAll('.page-btn').forEach(btn => {
            btn.onclick = function() {
                const p = parseInt(this.getAttribute('data-page'));
                routeCurrentPage = p;
                fetchRouteOrders(routeCurrentPage, routePageSize);
            };
        });
    }

    async function fetchActivityOrders(page = 1, size = 10, status = 'all') {
        try {
            let url = `http://localhost:8080/api/orders/activity?current=${page}&size=${size}`;
            if (status && status !== 'all') {
                url += `&status=${status}`;
            }
            const res = await fetch(url);
            const data = await res.json();
            if (data.code === 200 && data.data) {
                renderActivityOrders(data.data.records || []);
                renderActivityPagination(data.data.total || 0, data.data.current || 1, data.data.size || 10);
            } else {
                activityOrdersTbody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
                activityOrdersPagination.innerHTML = '';
            }
        } catch (e) {
            activityOrdersTbody.innerHTML = '<tr><td colspan="7">加载失败</td></tr>';
            activityOrdersPagination.innerHTML = '';
        }
    }

    function getActivityDisplayName(activity) {
        const map = {
            'hanfu': '汉服体验',
            'calligraphy': '书法体验',
            'tea': '茶艺体验',
            'food': '美食制作'
        };
        return map[activity] || activity || '';
    }

    function getStatusDisplayName(status) {
        const map = {
            'pending': '待使用',
            'certain': '已完成',
            'refund': '退款中',
            'expire': '已过期'
        };
        return map[status] || status || '';
    }

    function renderActivityOrders(list) {
        if (!list.length) {
            activityOrdersTbody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
            return;
        }
        activityOrdersTbody.innerHTML = list.map(order => `
            <tr>
                <td>${order.id}</td>
                <td>${order.username || ''}</td>
                <td>${getActivityDisplayName(order.activity)}</td>
                <td>${order.date || ''}</td>
                <td>${getStatusDisplayName(order.status)}</td>
                <td>${order.phone || ''}</td>
                <td>
                    <button class="btn-edit" data-order='${JSON.stringify(order)}' title="编辑"><i class="fa fa-pencil"></i></button>
                    <button class="btn-delete" title="删除"><i class="fa fa-trash"></i></button>
                </td>
            </tr>
        `).join('');
    }

    function renderActivityPagination(total, page, size) {
        const pageCount = Math.ceil(total / size);
        let html = '';
        for (let i = 1; i <= pageCount; i++) {
            html += `<button class="page-btn${i === page ? ' active' : ''}" data-page="${i}">${i}</button>`;
        }
        activityOrdersPagination.innerHTML = html;
        activityOrdersPagination.querySelectorAll('.page-btn').forEach(btn => {
            btn.onclick = function() {
                const p = parseInt(this.getAttribute('data-page'));
                activityCurrentPage = p;
                fetchActivityOrders(activityCurrentPage, activityPageSize, activityCurrentStatus);
            };
        });
    }

    // 切换显示时自动加载第一页
    function showRoutesSection() {
        routesSection.style.display = '';
        cultureSection.style.display = 'none';
        fetchRouteOrders(1, routePageSize);
    }
    function showCultureSection() {
        routesSection.style.display = 'none';
        cultureSection.style.display = '';
        fetchActivityOrders(1, activityPageSize, activityCurrentStatus);
    }
    menuLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            menuLinks.forEach(l => l.classList.remove('active'));
            this.classList.add('active');
            if (this.getAttribute('href') === '#routes') {
                showRoutesSection();
            } else if (this.getAttribute('href') === '#culture') {
                showCultureSection();
            }
        });
    });
    // 默认显示旅游路线管理并加载数据
    showRoutesSection();

    // Event listener for culture activity status filters
    activityFilterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            activityFilterBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            activityCurrentStatus = this.dataset.status;
            fetchActivityOrders(1, activityPageSize, activityCurrentStatus);
        });
    });

    // Logout functionality
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function() {
            localStorage.clear();
            window.location.href = 'login.html';
        });
    }

    // Modal functionality for Add and Edit
    const addRouteModal = document.getElementById('add-route-modal');
    const addActivityModal = document.getElementById('add-activity-modal');
    const editRouteModal = document.getElementById('edit-route-modal');
    const editActivityModal = document.getElementById('edit-activity-modal');
    
    const addRouteBtn = document.querySelector('#routes-manage-section .btn-add-route');
    const addActivityBtn = document.querySelector('#culture-manage-section .btn-add-route');

    // 动态加载用户下拉选项
    async function loadUserOptions(selectId, showId) {
        const select = document.getElementById(selectId);
        if (!select) return;
        select.innerHTML = '<option value="">请选择用户</option>';
        try {
            const res = await fetch('http://localhost:8080/login/getAllUsers');
            const data = await res.json();
            if (data.code === 200 && Array.isArray(data.data)) {
                data.data.forEach(user => {
                    const option = document.createElement('option');
                    option.value = user.id;
                    option.textContent = showId ? `${user.id} - ${user.username}` : user.username;
                    select.appendChild(option);
                });
            }
        } catch (e) {
            // 可选：select.innerHTML += '<option value="">加载失败</option>';
        }
    }

    function setupModal(modal, openBtn, userSelectId) {
        if (!modal || !openBtn) return;
        const closeBtn = modal.querySelector('.close-btn');

        openBtn.onclick = () => {
            modal.style.display = 'block';
            if (userSelectId) loadUserOptions(userSelectId, false);
        };
        closeBtn.onclick = () => modal.style.display = 'none';
        window.onclick = (event) => {
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        };

        const form = modal.querySelector('form');
        form.onsubmit = async (e) => {
            e.preventDefault();
            if (form.id === 'add-route-form') {
                // 新增旅游路线订单表单提交
                const userId = document.getElementById('route-username').value;
                const route = document.getElementById('route-name').value;
                const date = document.getElementById('route-date').value;
                const people = document.getElementById('route-people').value;
                const phone = document.getElementById('route-phone').value;
                try {
                    const res = await fetch('http://localhost:8080/routes', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            userId,
                            route,
                            date,
                            people,
                            phone
                        })
                    });
                    const data = await res.json();
                    if (data.code === 200) {
                        alert('新增成功！');
                        modal.style.display = 'none';
                        fetchRouteOrders(1, routePageSize);
                    } else {
                        alert('新增失败：' + (data.message || '未知错误'));
                    }
                } catch (err) {
                    alert('请求失败，请检查网络或后端服务');
                }
            } else if (form.id === 'add-activity-form') {
                // 新增文化活动订单表单提交
                const userId = document.getElementById('activity-username').value;
                const activity = document.getElementById('activity-name').value;
                const date = document.getElementById('activity-date').value;
                const phone = document.getElementById('activity-phone').value;
                const email = document.getElementById('activity-email').value;
                try {
                    const res = await fetch('http://localhost:8080/culture', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            userId,
                            activity,
                            date,
                            phone,
                            email,
                            status: 'pending'
                        })
                    });
                    const data = await res.json();
                    if (data.code === 200) {
                        alert('新增成功！');
                        modal.style.display = 'none';
                        fetchActivityOrders(1, activityPageSize, activityCurrentStatus);
                    } else {
                        alert('新增失败：' + (data.message || '未知错误'));
                    }
                } catch (err) {
                    alert('请求失败，请检查网络或后端服务');
                }
            } else {
                alert('表单提交成功！（此为演示，数据未发送）');
                modal.style.display = 'none';
            }
        };
    }

    setupModal(addRouteModal, addRouteBtn, 'route-username');
    setupModal(addActivityModal, addActivityBtn, 'activity-username');

    // 编辑旅游路线订单弹窗，用户名下拉显示id-username
    routeOrdersTbody.addEventListener('click', async function(e) {
        const editBtn = e.target.closest('.btn-edit');
        if (editBtn) {
            const order = JSON.parse(editBtn.dataset.order);
            document.getElementById('edit-route-id').value = order.id;
            await loadUserOptions('edit-route-username', true);
            document.getElementById('edit-route-username').value = order.userId;
            document.getElementById('edit-route-name').value = order.route;
            document.getElementById('edit-route-date').value = order.date;
            document.getElementById('edit-route-people').value = order.people;
            document.getElementById('edit-route-phone').value = order.phone;
            editRouteModal.style.display = 'block';
        }
    });

    activityOrdersTbody.addEventListener('click', async function(e) {
        const editBtn = e.target.closest('.btn-edit');
        if (editBtn) {
            const order = JSON.parse(editBtn.dataset.order);
            document.getElementById('edit-activity-id').value = order.id;
            await loadUserOptions('edit-activity-username', true);
            document.getElementById('edit-activity-username').value = order.userId;
            document.getElementById('edit-activity-name').value = order.activity;
            document.getElementById('edit-activity-date').value = order.date;
            document.getElementById('edit-activity-phone').value = order.phone;
            document.getElementById('edit-activity-email').value = order.email;
            editActivityModal.style.display = 'block';
        }
    });

    function setupEditModal(modal) {
        const closeBtn = modal.querySelector('.close-btn');
        closeBtn.onclick = () => modal.style.display = 'none';
        
        const form = modal.querySelector('form');
        form.onsubmit = async (e) => {
            e.preventDefault();
            if (form.id === 'edit-route-form') {
                // 编辑旅游路线订单表单提交
                const id = document.getElementById('edit-route-id').value;
                const userId = document.getElementById('edit-route-username').value;
                const route = document.getElementById('edit-route-name').value;
                const date = document.getElementById('edit-route-date').value;
                const people = document.getElementById('edit-route-people').value;
                const phone = document.getElementById('edit-route-phone').value;
                try {
                    const res = await fetch(`http://localhost:8080/routes/${id}`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            userId,
                            route,
                            date,
                            people,
                            phone
                        })
                    });
                    const data = await res.json();
                    if (data.code === 200) {
                        alert('修改成功！');
                        modal.style.display = 'none';
                        fetchRouteOrders(1, routePageSize);
                    } else {
                        alert('修改失败：' + (data.message || '未知错误'));
                    }
                } catch (err) {
                    alert('请求失败，请检查网络或后端服务');
                }
            } else if (form.id === 'edit-activity-form') {
                // 编辑文化活动订单表单提交
                const id = document.getElementById('edit-activity-id').value;
                const userId = document.getElementById('edit-activity-username').value;
                const activity = document.getElementById('edit-activity-name').value;
                const date = document.getElementById('edit-activity-date').value;
                const phone = document.getElementById('edit-activity-phone').value;
                const email = document.getElementById('edit-activity-email').value;
                try {
                    const res = await fetch(`http://localhost:8080/culture/${id}`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            userId,
                            activity,
                            date,
                            phone,
                            email
                        })
                    });
                    const data = await res.json();
                    if (data.code === 200) {
                        alert('修改成功！');
                        modal.style.display = 'none';
                        fetchActivityOrders(1, activityPageSize, activityCurrentStatus);
                    } else {
                        alert('修改失败：' + (data.message || '未知错误'));
                    }
                } catch (err) {
                    alert('请求失败，请检查网络或后端服务');
                }
            } else {
                alert('修改已保存！（此为演示，数据未发送）');
                modal.style.display = 'none';
            }
        };
    }
    
    setupEditModal(editRouteModal);
    setupEditModal(editActivityModal);

    // 旅游路线删除按钮事件
    routeOrdersTbody.addEventListener('click', function(e) {
        const delBtn = e.target.closest('.btn-delete');
        if (delBtn) {
            const order = JSON.parse(delBtn.previousElementSibling.dataset.order);
            deleteOrderInfo = { type: 'route', id: order.id };
            confirmDeleteModal.style.display = 'block';
        }
    });
    // 文化活动删除按钮事件
    activityOrdersTbody.addEventListener('click', function(e) {
        const delBtn = e.target.closest('.btn-delete');
        if (delBtn) {
            const order = JSON.parse(delBtn.previousElementSibling.dataset.order);
            deleteOrderInfo = { type: 'activity', id: order.id };
            confirmDeleteModal.style.display = 'block';
        }
    });
    // 取消删除
    cancelDeleteBtn.onclick = function() {
        confirmDeleteModal.style.display = 'none';
        deleteOrderInfo = null;
    };
    // 确认删除
    confirmDeleteBtn.onclick = async function() {
        if (deleteOrderInfo) {
            if (deleteOrderInfo.type === 'route') {
                // 旅游路线订单删除
                try {
                    const res = await fetch(`http://localhost:8080/routes/${deleteOrderInfo.id}`, {
                        method: 'DELETE'
                    });
                    const data = await res.json();
                    if (data.code === 200) {
                        alert('删除成功！');
                        fetchRouteOrders(1, routePageSize);
                    } else {
                        alert('删除失败：' + (data.message || '未知错误'));
                    }
                } catch (err) {
                    alert('请求失败，请检查网络或后端服务');
                }
            } else if (deleteOrderInfo.type === 'activity') {
                // 文化活动订单删除
                try {
                    const res = await fetch(`http://localhost:8080/culture/${deleteOrderInfo.id}`, {
                        method: 'DELETE'
                    });
                    const data = await res.json();
                    if (data.code === 200) {
                        alert('删除成功！');
                        fetchActivityOrders(1, activityPageSize, activityCurrentStatus);
                    } else {
                        alert('删除失败：' + (data.message || '未知错误'));
                    }
                } catch (err) {
                    alert('请求失败，请检查网络或后端服务');
                }
            } else {
                alert('已删除订单ID: ' + deleteOrderInfo.id + '（此为演示，未实际删除）');
            }
        }
        confirmDeleteModal.style.display = 'none';
        deleteOrderInfo = null;
    };
}); 